package proxy;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class JDKProxyDemo {
    // 需要动态代理的接口
    static interface Sister{
        void sing();
    }
    // 需要动态代理的实际对象
    static class Wan implements Sister{
        @Override
        public void sing() {
            System.out.println("I am wanqian.");
        }
    }
    // 需要动态代理的实际对象---没有实现接口
    static class Jin {
        public void sing() {
            System.out.println("I am Jinsha.");
        }
    }
    //JDK proxy
    static class ProxyCheng implements InvocationHandler{
        //要代理的真实对象
        private Object target;
        //构造方法，给要代理的真实对象赋值
        ProxyCheng (Object obj){
            this.target = obj;
        }
        public Object getInstance(){
            Object o = Proxy.newProxyInstance(target.getClass().getClassLoader(),target.getClass().getInterfaces(),this);
            return o;
        }
        @Override
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            System.out.println("introduce yourself...");
            // 执行调用方法(此方法执行前后，可以进行相关业务处理)
            Object result = method.invoke(target,args);
            System.out.println("score...");
            return result;
        }
    }
    public static void main(String[] args) {
        //创建被代理类的对象
        Sister wanqian = new Wan();
        //创建代理类的对象
        ProxyCheng proxyCheng = new ProxyCheng(wanqian);
        //获取动态代理类实例
        Sister proxySister = (Sister) proxyCheng.getInstance();
        System.out.println("JDK Dynamic object name: " + proxySister.getClass().getName());
        proxySister.sing();
    }
}
